from django.shortcuts import render

# Create your views here.
# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
from rest_framework import status
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User
from users.serializers import CreateUserSerializer


# POST /user/
class UserView(CreateAPIView):
    """注册用户的信息并保存"""
    serializer_class = CreateUserSerializer

    # def post(self, request):
    #     # 1. 校验用户在表单里传来的参数（参数的完整性，是否同意协议，手机号格式，手机号是否注册，短信码,俩次密码是否一样
    #     serializer = self.get_serializer(data=request.data)
    #
    #     serializer.is_valid(raise_exception=True)
    #     print(serializer.is_valid())
    #
    #     # 2. 将传来的参数保存
    #     serializer.save()  # create
    #
    #     # 3. 返回响应
    #     return Response(serializer.data, status=status.HTTP_201_CREATED)


class UsernameCountView(APIView):
    """
    用户名数量
    """

    def get(self, request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """
    手机号数量
    """

    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)
